﻿using System;
using System.Collections.Generic;

using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
namespace HZ.DrugTrade.Web.Enterprise.RelationQuery
{
    public partial class RelationQueryUnpack : BasePage
    {
        public RelationQueryUnpack()
        {
            this.ModuleNo = Module.分配送管理.ToString();
        }
        IBLL_Company IBC = Factory.BLL_Company();
        IBLL_SelectRelation iselectRelation = Factory.BLL_SelectRelation();
        //存放地区编号名称信息的字典
        Dictionary<string, string> dicRule = new Dictionary<string, string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (CurrentAccount.GetUser().UserRole.RoleID == "05")
                {
                    //
                    lblNav.Text = "<ul><li><a href=\"CompanyMaintain.aspx\">配送企业管理</a></li><li class=\"active\"><a href=\"RelationQueryUnpack.aspx\">配送产品管理</a></li><li><a href=\"DistributionRelationToQuery.aspx\">配送关系查询</a></li></ul>";

                    BangdinGvRelaion();
                }
                else
                {
                    HZ.DrugTrade.Model.Query.Company com = new HZ.DrugTrade.Model.Query.Company();
                    com.CompanyID = CurrentAccount.GetUser().Org.OrgID; ;
                    int outINt = 0;
                    IList<Company> lst = IBC.GetCompanyByWhere(com, 1, 1, out outINt);

                    if (lst != null && (lst[0].CompanyType == EnumCompanyType.配送企业 || lst[0].CompanyType == EnumCompanyType.生产企业直接配送 || lst[0].CompanyType == EnumCompanyType.经营企业直接配送))
                    {
                        Response.Redirect("DistributionRelationToConfirm.aspx");
                    }
                    else
                    {
                        lblNav.Text = "<ul><li><a href=\"CompanyMaintain.aspx\">配送企业管理</a></li><li class=\"active\"><a href=\"RelationQueryUnpack.aspx\">配送产品管理</a></li><li><a href=\"DistributionRelationToQuery.aspx\">配送关系查询</a></li><li ><a href=\"DistributionRelationToConfirm.aspx\">配送关系确认</a></li></ul>";
                        BangdinGvRelaion();
                    }
                }
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            BangdinGvRelaion();
        }
        /// <summary>
        /// 绑定事件
        /// </summary>
        private void BangdinGvRelaion()
        {
            HZ.DrugTrade.Model.Query.ProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.ProcureCatalog();
            procureCatalog.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.GoodsName = txtProductName.Text.Trim();
            procureCatalog.Outlookc = txtOutlookc.Text.Trim();
            procureCatalog.ProjectID = ddlProject.SelectedValue;
            procureCatalog.Unit = txtUnit.Text.Trim();
            procureCatalog.PinyinCode = this.txtpinyincode.Text.Trim();
            //procureCatalog.PinyinCode = this.txtPinyinCode.Text.Trim();
         
            procureCatalog.IsUsing = true;  // 只有是未撤废的产品才能进行配送企业的选择 by wang 2010-06-25 08:33:00
            procureCatalog.SortFields = " goodsid ";
            GvRelaion.AutoGenerateColumns = false;
            
            int totalrecord = 0;
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            IBLL_ProcurementBasic iDistribution = Factory.BLL_ProcurementBasic();
            this.GvRelaion.DataSource = iDistribution.GetProcureCatalogByWhere(procureCatalog, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalrecord);
            GvRelaion.DataBind();
            AspNetPager1.RecordCount = totalrecord;
            if (ddlProject.SelectedValue == "0002")
            {
                btnCheck.Visible = false;
                btnSubmit.Visible = false;
                hzbtnCheckConfirm.Visible = false;
                hzbtnToSubmit.Visible = false;
            }
            else
            {
                btnCheck.Visible = true;
                btnSubmit.Visible = true;
                hzbtnCheckConfirm.Visible = true;
                hzbtnToSubmit.Visible = true;
            }
        }
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BangdinGvRelaion();
        }

        /// <summary>
        /// 将给定的url加上script 实现页面跳转
        /// 针对button 的 onclintclick 新窗口打开
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string OpenURLScript(string str)
        {
            int index = str.IndexOf("?");
            //给url加returnUrl,值为当前页面的Url
            if (index != -1)
            {
                str += "&" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            else
            {
                str += "?" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            string strScript = "if(!this.disabled){window.open('" + str + "');} return false;";
            return strScript;
        }
        /// <summary>
        /// 检查配送关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCheck_Click(object sender, EventArgs e)
        {
            //获取该企业的中标目录

            HZ.DrugTrade.Model.Query.ProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.ProcureCatalog();
            procureCatalog.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.SortFields = " ProcureCatalogID ";
            procureCatalog.IsUsing = true;//只有正常采购才能进行检查配送关系
            procureCatalog.ProjectID = ddlProject.SelectedItem.Value;
            GvRelaion.AutoGenerateColumns = false;
            int totalrecord = 0;
            IBLL_ProcurementBasic iDistribution = Factory.BLL_ProcurementBasic();
            //IList<HZ.DrugTrade.Model.View.ProcureCatalog> lst =iDistribution.GetProcureCatalogByWhere(procureCatalog, 1,0, out totalrecord);
            DataTable dtAll = iDistribution.GetProcureCatalogDTByWhere(procureCatalog, 1, 0, out totalrecord);

            if (totalrecord > 0)
            {
                dtAll.Columns.Add(new DataColumn("AreaNames", Type.GetType("System.String")));
                
                //获取企业的配送关系
                string strWhere = " ";
                //非拒绝的配送关系
                strWhere += " and companyid_TB='" + CurrentAccount.GetUser().Org.OrgID + "' and status<>'已拒绝' order by ProcureCatalogID ";

                int totalCount = 0;
                DataTable dt = iselectRelation.GetSelectRelationByProcureCatalogID(strWhere, 1, 0, out totalCount);
                if (totalrecord <= 0)
                {
                    foreach (DataRow row in dtAll.Rows)
                    {
                        row["AreaNames"] = "全区";
                    } 
                }
                else
                {
                    #region 十二盟市信息

                    if (dicRule.Count != 12)
                    {
                        dicRule.Clear();
                        dicRule.Add("150100", "呼和浩特市");
                        dicRule.Add("150200", "包头市");
                        dicRule.Add("150300", "乌海市");
                        dicRule.Add("150400", "赤峰市");
                        dicRule.Add("150500", "通辽市");
                        dicRule.Add("150600", "鄂尔多斯市");
                        dicRule.Add("150700", "呼伦贝尔市");
                        dicRule.Add("150800", "巴彦淖尔市");
                        dicRule.Add("150900", "乌兰察布市");
                        dicRule.Add("152200", "兴安盟");
                        dicRule.Add("152500", "锡林郭勒盟");
                        dicRule.Add("152900", "阿拉善盟");
                    }
                    #endregion 
                    //配送关系检查
                    for (int _index = 0; _index < totalrecord; _index++)
                    {
                        string strProcureCatalogID = dtAll.Rows[_index]["ProcureCatalogID"].ToString();

                        DataRow[] dataRows = dt.Select("ProcureCatalogID='" + strProcureCatalogID + "'", "AreaID");

                        if (dataRows.Length == 0)
                        {
                            dtAll.Rows[_index]["AreaNames"] = "全区";
                        }
                        else
                        {
                            string strAreaNames = string.Empty;

                            foreach (DataRow dr in dataRows)
                            {
                                strAreaNames += dr["AreaID"].ToString() + ",";
                            }

                            dtAll.Rows[_index]["AreaNames"] = GetUnDisAreaNames(strAreaNames);
                        }
                    }

                    //配送关系检查
                    for (int _index = 0; _index < dtAll.Rows.Count; )
                    {

                        string strAreaNames = dtAll.Rows[_index]["AreaNames"].ToString();
                        if (strAreaNames.Length <= 0)
                        {
                            dtAll.Rows.RemoveAt(_index);
                        }
                        else
                        {
                            _index++;
                        }
                    } 

                    this.grvCheckList.DataSource = dtAll;
                    this.grvCheckList.DataBind();

                    if (this.grvCheckList.Rows.Count == 0)
                    {
                        this.btnSubmit.Enabled = true;
                    }
                    else
                    {
                        this.btnSubmit.Enabled = false;
                    }

                }
            }
            else
            {
                btnSubmit.Enabled = false;
            }
        }
        /// <summary>
        /// 获取未配送的地区
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        protected string GetUnDisAreaNames(string strIDs)
        {
            string strAreaNames = string.Empty;
            foreach (string AreaID in dicRule.Keys)
            {
                if (strIDs.Contains(AreaID) == false)
                {
                    strAreaNames += dicRule[AreaID] + "、";
                }
            }
            return strAreaNames;
        }
        /// <summary>
        /// 提交配送企业确认配送关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            btnCheck_Click(new object(), EventArgs.Empty); //提交前先检查，以防两个浏览器操作时失误  modiy by ysm 20130320
            if (btnSubmit.Enabled)
            {
                if (iselectRelation.UpdateSelectRelation(CurrentAccount.GetUser().Org.OrgID) == 1)
                {
                    PageInfo("操作成功！", Request.RawUrl);
                }
                else
                {
                    PageError("操作失败！", Request.RawUrl);
                }
            }
        }
        /// <summary>
        /// 检查确认情况
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnCheckConfirm_Click(object sender, EventArgs e)
        {
            #region 代码逻辑和check函数一样
            //获取该企业的中标目录

            HZ.DrugTrade.Model.Query.ProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.ProcureCatalog();
            procureCatalog.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.IsUsing = true;//只有正常采购才能进行检查配送关系
            procureCatalog.SortFields = " ProcureCatalogID ";
            procureCatalog.ProjectID = ddlProject.SelectedItem.Value;
            GvRelaion.AutoGenerateColumns = false;
            int totalrecord = 0;
            IBLL_ProcurementBasic iDistribution = Factory.BLL_ProcurementBasic();
            //IList<HZ.DrugTrade.Model.View.ProcureCatalog> lst =iDistribution.GetProcureCatalogByWhere(procureCatalog, 1,0, out totalrecord);
            DataTable dtAll = iDistribution.GetProcureCatalogDTByWhere(procureCatalog, 1, 0, out totalrecord);

            if (totalrecord > 0)
            {
                dtAll.Columns.Add(new DataColumn("AreaNames", Type.GetType("System.String")));

                //获取企业的配送关系
                string strWhere = " ";
                //非拒绝的配送关系
                strWhere += " and companyid_TB='" + CurrentAccount.GetUser().Org.OrgID + "' and (status='已同意' or  status='可配送' ) order by ProcureCatalogID ";

                int totalCount = 0;
                DataTable dt = iselectRelation.GetSelectRelationByProcureCatalogID(strWhere, 1, 0, out totalCount);
                if (totalrecord <= 0)
                {
                    foreach (DataRow row in dtAll.Rows)
                    {
                        row["AreaNames"] = "全区";
                    }
                }
                else
                {
                    #region 十二盟市信息
                    if (dicRule.Count != 12)
                    {
                        dicRule.Clear();
                        dicRule.Add("150100", "呼和浩特市");
                        dicRule.Add("150200", "包头市");
                        dicRule.Add("150300", "乌海市");
                        dicRule.Add("150400", "赤峰市");
                        dicRule.Add("150500", "通辽市");
                        dicRule.Add("150600", "鄂尔多斯市");
                        dicRule.Add("150700", "呼伦贝尔市");
                        dicRule.Add("150800", "巴彦淖尔市");
                        dicRule.Add("150900", "乌兰察布市");
                        dicRule.Add("152200", "兴安盟");
                        dicRule.Add("152500", "锡林郭勒盟");
                        dicRule.Add("152900", "阿拉善盟");
                    }
                    #endregion
                    //配送关系检查
                    for (int _index = 0; _index < totalrecord; _index++)
                    {
                        string strProcureCatalogID = dtAll.Rows[_index]["ProcureCatalogID"].ToString();

                        DataRow[] dataRows = dt.Select("ProcureCatalogID='" + strProcureCatalogID + "'", "AreaID");

                        if (dataRows.Length == 0)
                        {
                            dtAll.Rows[_index]["AreaNames"] = "全区";
                        }
                        else
                        {
                            string strAreaNames = string.Empty;

                            foreach (DataRow dr in dataRows)
                            {
                                strAreaNames += dr["AreaID"].ToString() + ",";
                            }

                            dtAll.Rows[_index]["AreaNames"] = GetUnDisAreaNames(strAreaNames);
                        }
                    }

                    //配送关系检查
                    for (int _index = 0; _index < dtAll.Rows.Count; )
                    {

                        string strAreaNames = dtAll.Rows[_index]["AreaNames"].ToString();
                        if (strAreaNames.Length <= 0)
                        {
                            dtAll.Rows.RemoveAt(_index);
                        }
                        else
                        {
                            _index++;
                        }
                    }

                    this.grvConfirmList.DataSource = dtAll;
                    this.grvConfirmList.DataBind();

                    if (this.grvConfirmList.Rows.Count == 0)
                    {
                        this.hzbtnToSubmit.Enabled = true;
                    }
                    else
                    {
                        this.hzbtnToSubmit.Enabled = false;
                    }

                }
            }
            else
            {
                hzbtnToSubmit.Enabled = false;
            }
            #endregion 
        }
        /// <summary>
        /// 提交确认信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnToSubmit_Click(object sender, EventArgs e)
        {
            //提交确认信息前再次check
            //暂时注释
            hzbtnCheckConfirm_Click(new object(), EventArgs.Empty);

            if (this.hzbtnToSubmit.Enabled)
            {
                int result = iselectRelation.UpdateSelectRelation(CurrentAccount.GetUser().Org.OrgID, 3);
                if (result == 1)
                {
                    PageInfo("操作成功！", Request.RawUrl);
                }
                else if (result == 2)
                {
                    PageError("有未提交和配送企业未确认的品规！", Request.RawUrl);
                }
                else if (result == 3)
                {
                    PageError("有未提交的品规！", Request.RawUrl);
                }
                else if (result == 4)
                {
                    PageError("有配送企业未确认的品规！", Request.RawUrl);
                }
                else
                {
                    PageError("已经确认过！", Request.RawUrl);
                }
            }
            else
            {
                HZ.Web.MessageBox.Show("存在未确认的配送区域！");
            }
        }
    }
}
